/**
 * mooc公共方法
 */
(function(global){
	/**
	 * 定义全局函数对象 define出来的
	 */
	var mapping = {};
	/**
	 * 缓存,正在用到的对象,函数中return 出来的,这样就不需要重复执行函数
	 */
	var cache = {};
	/**
	 * @description 模块定义
	 * @param {String} id id
	 * @param {Function} func 对应的函数对象
	 */
	global.define = function(id, func) {
		mapping[id] = func;
	};
	/**
	 * @description 生成模块对象,并采用本地缓存
	 * @param {String} id
	 */
	global.require = function(id) {
		if (!/\.js$/.test(id)) {
			id += '.js';
		}
		if (cache[id]) {
			return cache[id];
		} else {
			if (mapping[id]) {
				cache[id] = mapping[id]({})
			}
			return cache[id];
		}
	};
	/**
	 * @description 定义模块功能--通用框架类
	 */
	define('scripts/Core/MobileFrame.js', function(exports) {
		/**
		 * 空函数
		 */
		exports.noop = function() {};
		/**
		 * @description each遍历操作
		 * @param {type} elements
		 * @param {type} callback
		 * @returns {global}
		 */
		exports.each = function(elements, callback, hasOwnProperty) {
			if (!elements) {
				return this;
			}
			if (typeof elements.length === 'number') {
				[].every.call(elements, function(el, idx) {
					return callback.call(el, idx, el) !== false;
				});
			} else {
				for (var key in elements) {
					if (hasOwnProperty) {
						if (elements.hasOwnProperty(key)) {
							if (callback.call(elements[key], key, elements[key]) === false) return elements;
						}
					} else {
						if (callback.call(elements[key], key, elements[key]) === false) return elements;
					}
				}
			}
			return global;
		};
		/**
		 * @description plusReady
		 * @param {Function} callback
		 * @returns {global} 返回的是global
		 */
		exports.plusReady = function(callback) {
			if (window.plus) {
				setTimeout(function() { //解决callback与plusready事件的执行时机问题(典型案例:showWaiting,closeWaiting)
					callback();
				}, 0);
			} else {
				document.addEventListener("plusready", function() {
					callback();
				}, false);
			}
			return global;
		};
		/**
		 * @description 判断网络状态
		 */
		function GetNetWorkState() {
			var NetStateStr = '未知';
			var types = {};
			types[plus.networkinfo.CONNECTION_UNKNOW] = "未知";
			types[plus.networkinfo.CONNECTION_NONE] = "未连接网络";
			types[plus.networkinfo.CONNECTION_ETHERNET] = "有线网络";
			types[plus.networkinfo.CONNECTION_WIFI] = "WiFi网络";
			types[plus.networkinfo.CONNECTION_CELL2G] = "2G蜂窝网络";
			types[plus.networkinfo.CONNECTION_CELL3G] = "3G蜂窝网络";
			types[plus.networkinfo.CONNECTION_CELL4G] = "4G蜂窝网络";
			NetStateStr = types[plus.networkinfo.getCurrentType()];

			return NetStateStr;
		};
		/**
		 * @description 判断是否有网络
		 */
		exports.IsNetWorkCanUse = function() {
			var IsCanUseNetWork = false;
			if (GetNetWorkState() == '未知' || GetNetWorkState() == '未连接网络') {
				IsCanUseNetWork = false;
			} else {
				IsCanUseNetWork = true;
			}
			return IsCanUseNetWork;
		};
		/**
		 * @description 判断是否存在js或者css
		 * @param {String} name js或者css的名字
		 */
		exports.IsInclude = function(name) {
			var js = /js$/i.test(name);
			var es = document.getElementsByTagName(js ? 'script' : 'link');
			for (var i = 0; i < es.length; i++)
				if (es[i][js ? 'src' : 'href'].indexOf(name) != -1) return true;
			return false;
		};
		return exports;
	});
	//*** 通用框架类完毕
	/**
	 * @description 定义模块功能-常用工具类
	 */
	define('scripts/Core/MobileFrame_CommonUtil.js', function(exports) {
		/**
		 * @description 比较两个版本大小
		 * 比较版本大小，如果新版本nowVersion大于旧版本OldResourceVersion则返回true，否则返回false
		 * @param {String} OldVersion
		 * @param {String} nowVersion
		 */
		exports.compareVersion = function(OldVersion, nowVersion) {
			if (!OldVersion || !nowVersion || OldVersion == '' || nowVersion == '') {

				return false;
			}
			//第二份参数 是 数组的最大长度
			var OldVersionA = OldVersion.split(".", 4);
			var nowVersionA = nowVersion.split(".", 4);
			for (var i = 0; i < OldVersionA.length && i < nowVersionA.length; i++) {
				var strOld = OldVersionA[i];
				var numOld = parseInt(strOld);
				var strNow = nowVersionA[i];
				var numNow = parseInt(strNow);
				//小版本到高版本
				if (numNow > numOld
					//||strNow.length>strOld.length
				) {
					return true;
				} else if (numNow < numOld) {
					return false;
				}
			}
			//如果是版本  如 1.6 - 1.6.1
			if (nowVersionA.length > OldVersionA.length && 0 == nowVersion.indexOf(OldVersion)) {
				return true;
			}
		};
		/**
		 * @description 得到相对路径对应的key,这个key可以使缓存池的或者是本地缓存键值
		 * 主要作用是去除非法字符
		 * @param {String} relativePath
		 */
		exports.getRelativePathKey = function(relativePath) {
			var finalKey =
				//					relativePath.replace('\/', '').replace('.', '').replace('\/', '')
				//					.replace('_download', '').replace('jpg', '');
				relativePath.replace(/[&\|\\\*^%$#@\-.\/]/g, "");
			return finalKey;
		};
		/**
		 * @description 更改url类型,去除cache,因为cache会造成一些困扰
		 * @param {String} url 传入的url
		 */
		exports.changImgUrlTypeWithRandomKey = function(url) {
			url = url || '';
			if (url.indexOf('?') != -1) {
				url += '&timeRandKey=' + Math.random();
			} else {
				url += '?timeRandKey=' + Math.random();
			}
			return url;
		};
		exports.encodeUrl=function(url){
			//判断需不需要将路径进行编码,如果是中文路径,需要编码
			var regChinese = /[\u4E00-\u9FA5]/g;
			var tmpLoadUrl = url.replace(regChinese, 'chineseRemoveAfter');
			if (tmpLoadUrl.indexOf('chineseRemoveAfter') != -1) 
					url = encodeURI(url);
					return url;
		};
		return exports;
	});
	//*** 常用工具类完毕
	/**
	 * @description 定义模块功能-File工具类
	 */
	define('scripts/Core/MobileFrame_FileUtil.js', function(exports) {
		var MobileFrame = require('scripts/Core/MobileFrame.js');
		/**
		 * @description 删除指定路径的文件
		 * @param {String} relativePath  绝对路径或相对路径例如:  _downloads/imgs/test.jpg
		 * @param {Function} successCallback  删除成功回调
		 * @param {Function} errorCallback  失败回调
		 */
		exports.delFile = function(relativePath, successCallback, errorCallback) {
			if (!relativePath) {
				return;
			}
			MobileFrame.plusReady(function() {
				plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {
					entry.remove(function(entry) {
						if (successCallback && typeof(successCallback) == 'function') {
							successCallback(true);
						}
					}, function(e) {
						if (errorCallback && typeof(errorCallback) == 'function') {
							errorCallback('删除文件失败!');
						}
					});
				}, function() {
					if (errorCallback && typeof(errorCallback) == 'function') {
						errorCallback('打开文件路径失败!');
					}
				});
			});
		};
		return exports;
	});
	//*** File工具类完毕
	/**
	 * 本地缓存工具类
	 * start
	 */
	define('script/localStorageUtils.js',function(Utils){
		/**
		 * 设置缓存
		 * @param {Object} key
		 */
		Utils.getSessionItem=function(key){
				if(key==null)return null;
			    var item=localStorage.getItem(key);
			    try{
				    if(item!=null)item=JSON.parse(item);
			     }catch(e){}
			    return item;
			
		};
		/**
		 * 设置缓存
		 * @param {Object} key
		 * @param {Object} value
		 */
		Utils.setSessionItem=function(key,value){
				if(key==null)return;
			    value = (value != null) ? value : '';
			    value = (typeof(value) == 'string') ? value : JSON.stringify(value);
			   localStorage.setItem(key,value);
			
		};
		return Utils;
	});
	//本地缓存工具end
	/**
	 * 下载工具类
	 */
		/**
	 * 下载工具类
	 */
	define('script/downloadUtils.js',function(downloadUtils){
		
		/**
		 * 默认的options
		 */
		var defaultSettingOptions = {
			//默认的下载缓存目录-存到应用的downloads/downloadFiles下
			'downloadStoragePath': "_downloads/downloadFiles2/",
			//本地缓存的时间戳,毫秒单位,默认为1天
			'fileCacheTimeStamp': 1000 * 60 * 60 * 24 * 1,
			//同时最多的downloader 并发下载数目,默认为3个
			'concurrentDownloadCount': 10,
			//超时请求时间
			'timeout': 10,
			//超时请求后的重试次数
			'retryInterval': 3,
			//单个下载任务最大的请求时间,防止一些机型上无法触发错误回调,单位毫秒,默认10秒
			'maxTimeSingleDownloadTaskSpend': 1000 * 10,
			//获取相对路径的函数,如果不传,则用默认的路径处理方法
			'getRelativePathFromLoadUrlCallback': null,
			//监听进度的步长
			'ListenerProgressStep':5
		};
		/**
		 * 常用工具类
		 */
		var commonUtils=require('scripts/Core/MobileFrame_CommonUtil.js');
		var MobileFrame = require('scripts/Core/MobileFrame.js');
		/**
		 * 下载文件
		 * @param {Object} loadUrl
		 */
		downloadUtils.downloadFile=function(loadUrl,callbackOptions){
			if(loadUrl==null)return;
			loadUrl=commonUtils.encodeUrl(loadUrl);//中文转码
			callbackOptions = callbackOptions || {};
			//获得相对路径
			var downloadUtils=require('script/downloadUtils.js');
			var relativePath=downloadUtils.getRelativePathFromLoadUrl(loadUrl);
			//检查文件是否已存在,如果存在就采取本地文件,否则重新获取
			plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {
		    //如果文件存在,则直接回调本地路径
			callbackOptions.successDownload && callbackOptions.successDownload(relativePath, true);
			}, function(e) {
				MobileFrame.plusReady(function(){
				   startToDownloadFromNet(loadUrl, callbackOptions);	
				});
			});
		};
		/**
		 * 开始下载
		 * @param {Object} loadUrl
		 * @param {Object} callbackOptions
		 */
		function startToDownloadFromNet(loadUrl, callbackOptions){
			if(MobileFrame.IsNetWorkCanUse()){
				var downloadUtils=require('script/downloadUtils.js');
				var relativePath = downloadUtils.getRelativePathFromLoadUrl(loadUrl);
			if (relativePath == null)return;
			callbackOptions = callbackOptions || {};
			//下载参数
			var options = {
				filename: relativePath,
				timeout: defaultSettingOptions['timeout'],
				retryInterval: defaultSettingOptions['retryInterval']
			};
			//存一个最原始的地址,缓存是根据最原始的地址来的
			var originalUrl = loadUrl;
			//解决ios的网络缓存问题
			loadUrl = commonUtils.changImgUrlTypeWithRandomKey(loadUrl);
			//1.下载之前的回调
			callbackOptions.beforeDownload && callbackOptions.beforeDownload();
			//2.创建下载任务
			var dtask = plus.downloader.createDownload(loadUrl,
				options,
				function(d, status) {
					
				});
			   dtask.start();
			}else{
				callbackOptions.errorDownload && callbackOptions.errorDownload('下载失败:' + '没有网络!' + ',url:' + loadUrl);
			}
		};
		/**
		 * 获得存储相对路径
		 * @param {Object} loadUrl
		 */
	    downloadUtils.getRelativePathFromLoadUrl=function(loadUrl){
	    	var relativePath = null;
				//采用默认的路径处理
				//获取图片后缀,如果没有获取到后缀
				var fileSuffix = loadUrl.substring(loadUrl.lastIndexOf(".") + 1, loadUrl.length);
				fileSuffix = fileSuffix || 'file';
				//更换存储方式,变为将整个路径存储下来,然后去除非法字符
				var regIllegal = /[&\|\\\*^%$#@\-:.?\/=!]/g;
				//获取文件名字
				var fileName = loadUrl.replace(regIllegal, '');
				//最终的名字
				var finalFileFullName = fileName + '.' + fileSuffix;
				relativePath = defaultSettingOptions['downloadStoragePath'] + finalFileFullName;
			return relativePath;
	    };
	    /**
		 * 获取缓存本地绝对路径,播放路径
		 * @param {String} url
		 * @return 本地有缓存则返回本地路径，
		 */
		downloadUtils.getLocalAbsoluteUrl=function(url) {
			var localUrl=null;
			if (url == null)
				return localUrl;
			var downloadUtils=require('script/downloadUtils.js');
			var relativeUrl=downloadUtils.getRelativePathFromLoadUrl(url);
			if(relativeUrl!=null)localUrl=plus.io.convertLocalFileSystemURL(relativeUrl);
			return localUrl;
		};
	    return downloadUtils;
	});
	/**
	 * localStorage缓存管理
	 * start
	 */
	define('script/localStorageManagers.js',function(localStorageManagers){
		/**
		 * 用户id缓存
		 */
		var useridSessionkey="moocuserid_cache2";
		/**
		 * 同步课程缓存session头部
		 */
		var syncCourseSessionkey_head="syncCourseList_Sessionkey_cache2_";
		/**
		 * 同步课堂资源缓存头部
		 */
		var resourcelistSessionKey_head="resourceList_Sessionkey_cache2_";
		/**
		 * 下载资源缓存头部
		 */
		var downloadResourceSessionkey_head="downloadResource_Sessionkey_cache2_";
		/**
		 * 本地缓存工具类
		 */
		var localStorageUtils=require('script/localStorageUtils.js');
		
		/**
		 * 获得缓存用户id
		 */
		localStorageManagers.getUseridSession=function(){
			var userid=localStorageUtils.getSessionItem(useridSessionkey);
			return userid;
		};
		/**
		 * 设置用户id缓存
		 * @param {Object} userid
		 */
		localStorageManagers.setUseridSession=function(userid){
			localStorageUtils.setSessionItem(useridSessionkey,userid);
		};
		/**
		 * 同步课堂key:syncCourseSessionkey_head+用户id
		 */
		function getSynccourseKey(){
			var localStorageManagers=require('script/localStorageManagers.js');
			var synccourseKey=syncCourseSessionkey_head+localStorageManagers.getUseridSession();
			return synccourseKey;
		}
		/**
		 * 获得缓存课程
		 */
		localStorageManagers.getSynccourseSession=function(){
			var synccourseKey=getSynccourseKey();
			var courseitem=localStorageUtils.getSessionItem(synccourseKey);
			try{
			courseitem=JSON.parse(courseitem);
			}catch(e){}
			return courseitem;
		};
		/**
		 * 保存课程缓存
		 * @param {Object} courseList
		 */
		localStorageManagers.setSynccourseSession=function(courseList){
			var synccourseKey=getSynccourseKey();
			localStorageUtils.setSessionItem(synccourseKey,courseList);
			
		};
		/**
		 * 同步课堂资源缓存key
		 */
		function getSyncResourceSessionkey(courseid){
			var key=resourcelistSessionKey_head+localStorageUtils.getSessionItem(useridSessionkey)+courseid;
			return key;
		}
		/**
		 * 获得资源列表缓存
		 * @param {Object} courseid
		 */
		localStorageManagers.getResourcelistSession=function(courseid){
			var key=getSyncResourceSessionkey(courseid);
			var resourceItem=localStorageUtils.getSessionItem(key);
			try{
				resourceItem=JSON.parse(resourceItem);
			}catch(e){}
			return resourceItem;
		};
		/**
		 * 设置资源缓存
		 * @param {Object} courseid
		 * @param {Object} resourceList
		 */
		localStorageManagers.setResourcelistSession=function(courseid,resourceList){
			var key=getSyncResourceSessionkey(courseid);
			localStorageUtils.setSessionItem(key,resourceList);
		}
		/**
		 * 同步课堂资源下载记录key
		 */
		function getDownresourceSessionkey(){
			var key=downloadResourceSessionkey_head+localStorageUtils.getSessionItem(useridSessionkey);
			return key;
		}
		/**
		 * 获取资源缓存
		 */
		localStorageManagers.getDownloadResourceSession=function(){
			var key=getDownresourceSessionkey();
			var downloadResItem=localStorageUtils.getSessionItem(key);
			try{
				downloadResItem=JSON.parse(downloadResItem);
			}catch(e){}
			return downloadResItem;
		}
		/**
		 * 设置资源下载缓存
		 * @param {Object} downloadRes
		 */
		localStorageManagers.setDownloadResourceSession=function(downloadRes){
			var key=getDownresourceSessionkey();
			localStorageUtils.setSessionItem(key,downloadRes);
		}
		/**
		 * 插入一个下载对象
		 * @param {Object} courseid
		 * @param {Object} item
		 */
		localStorageManagers.pushDownresourceSessionItem=function(item){
			var localStorageManagers=require('script/localStorageManagers.js');
			var downloadResSession=localStorageManagers.getDownloadResourceSession();
			if(downloadResSession==null)downloadResSession=new Array();
			downloadResSession.push(item);
			localStorageManagers.setDownloadResourceSession(downloadResSession);
		}
		/**
		 * 移除一个下载对象
		 * @param {Object} courseid
		 * @param {Object} item
		 */
		localStorageManagers.removeDownresourceSessionItem=function(courseid,catalogid,resid){
			var localStorageManagers=require('script/localStorageManagers.js');
			var downloadResSession=localStorageManagers.getDownloadResourceSession();
			if(downloadResSession==null)return false;
			for (var i = 0; i < downloadResSession.length || 0; i++) {
				//alert(downloadResSession[i].catalogid+":"+catalogid+";"+downloadResSession[i].resid+":"+resid);
				if (downloadResSession[i].catalogid==catalogid&&downloadResSession[i].resid==resid) {
					downloadResSession.splice(i, 1);
				}
			}
			localStorageUtils.setSessionItem(getDownresourceSessionkey(), JSON.stringify(downloadResSession));
		}
		return localStorageManagers;
	});
	//本地缓存管理end
})(this);
